package com.startx.core.system.param;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import com.startx.core.mvc.define.BodyType;
import com.startx.core.tools.JsonTool;
import com.startx.core.tools.xml.XmlReader;

import io.netty.buffer.ByteBuf;

/**
 * HTTP请求体
 * @author minghu.zhang
 */
public class HttpBody {
	
	/**
	 * 字节缓冲区
	 */
	private ByteBuf buf;
	/**
	 * 请求响应体类型
	 */
	private BodyType type;
	/**
	 * 参数值
	 */
	private Map<String,?> map;
	
	public HttpBody(ByteBuf buf,BodyType type) {
		this.buf = buf;
		this.type = type;
	}
	
	/**
	 * 获取字节缓冲区
	 * @return
	 */
	public ByteBuf body() {
		return buf;
	}
	
	/**
	 * 获取字节数组
	 * @return
	 */
	private byte[] bytes() {
		byte[] body = new byte[buf.readableBytes()];

		buf.getBytes(0, body);
		buf.release();
		
		return body;
	}
	
	/**
	 * 获取map参数
	 * @return
	 */
	public Map<String,?> getMap() {
		try {
			
			if(Objects.isNull(map)) {
				String body = new String(bytes(),"UTF-8");
				
				if(type.equals(BodyType.JSON)) {
					map = JsonTool.json2map(body);
				} else if(type.equals(BodyType.XML)) {
					map = XmlReader.parseXml(body);
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			map = new HashMap<>();
		}
		
		return map;
	}
}
